﻿using System;
using System.Globalization;
using Hvam.SharePoint.Search.Query.Site.Models;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Hvam.SharePoint.Search.Query.Site.ResultSteps
{
    internal class WriteResultStep : SiteSearchResultStep
    {
        public WriteResultStep(SiteSearchQuery query) : base(query)
        {
        }

        public override SiteSearchResult Process(SiteSearchResult result)
        {
            if (!result.Properties.ContainsKey("write") &&
                Query.RequestedProperties.Contains("write") &&
                Query.RequestedFields.ContainsKey("modified"))
            {
                var item = result.ListItem;
                var write = item[SPBuiltInFieldId.Modified];
                if (write is DateTime)
                {
                    var dateTime = (DateTime) write;
                    var dateTimeUtc = dateTime.ToUniversalTime();

                    const SPDateFormat dateFormat = SPDateFormat.DateOnly;

                    var web = Query.Web;

                    var user = web.CurrentUser;
                    
                    var siteCulture = GetDisplayCulture(web, user);

                    string value;
                    if (user != null && user.RegionalSettings != null)
                    {
                        value = user.RegionalSettings.TimeZone.UTCToLocalTime(dateTimeUtc).ToString("d", siteCulture);
                    } 
                    else 
                    {
                        value = SPUtility.FormatDate(web, dateTimeUtc, dateFormat);
                    } 
        
                    result.Properties.Add("write", value);
                }
            }

            return result;
        }

        internal static CultureInfo GetDisplayCulture(SPWeb web, SPUser user)
        {
            if (user != null && user.RegionalSettings != null)
            {
                return new CultureInfo((int) user.RegionalSettings.LocaleId);
            }
            if (web != null)
            {
                return web.Locale;
            }
            return CultureInfo.CurrentCulture;
        }
    }
}
